package com.wootion.cims.module.systemsetting.user.controller;
import com.alibaba.fastjson.JSONObject;
import com.wootion.cims.general.utils.PasswprdUtil;
import com.wootion.cims.module.systemsetting.dictionary.model.LogAnotion;
import com.wootion.cims.module.systemsetting.user.model.User;
import com.wootion.cims.module.systemsetting.user.service.SysUserService;
import com.wootion.cims.response.ResponseResult;
import com.wootion.cims.response.ResultCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Optional;

/**
 * 用户管理
 */
@RestController
@RequestMapping("/sysuser")
@Api(value = "用户管理")
public class SysUserController {
    
    @Resource
    SysUserService sysUserService;

    @RequiresAuthentication
    @PostMapping("/save")
    @LogAnotion(type = "新增",value = "0",incident = "账号信息",prefixContent = "用户名")
    @ApiOperation(value = "用户管理-用户新增", httpMethod = "POST", notes = "{\"password\":\"123456\",\"role\":\"123456\",\"tel\":\"123456\",\"remark\":\"123456\",\"communitys\":[\"123\",\"465\"],\"username\":\"123456\"}")
    public ResponseResult save(@RequestBody JSONObject jsonObject) {

        if (!Optional.ofNullable(jsonObject.getString("username")).isPresent() ||
                !Optional.ofNullable(jsonObject.getString("firstPassword")).isPresent() ||
                !Optional.ofNullable(jsonObject.getString("tel")).isPresent()) {
            return ResponseResult.builder().code(ResultCode.PARAM_NOT_COMPLETE.getCode()).message(ResultCode.PARAM_NOT_COMPLETE.getMessage()).build();
        }

        String password = jsonObject.getString("firstPassword");

        boolean username = PasswprdUtil.contains(password, 0, jsonObject.getString("username"), 0);

        if (username){
            return ResponseResult.builder().code(ResultCode.PARAM_NOT_COMPLETE.getCode()).message("所设密码包含了用户名").build();
        }

        JSONObject accel = PasswprdUtil.accel(password);

//*        if (!accel.getBoolean("status")){
//            return ResponseResult.builder().code(ResultCode.PARAM_NOT_COMPLETE.getCode()).message(jsonObject.getString("messages")).build();
//        }
        return sysUserService.insert(jsonObject);
    }
    
    @RequiresAuthentication
    @PostMapping("/update")
    @ApiOperation(value = "用户管理-用户修改", httpMethod = "POST", notes = "{\"id\":\"255762da-3072-4b60-898b-5bc8142250c6\",\"password\":\"123456\",\"role\":\"741\",\"tel\":\"123456\",\"remark\":\"123456\",\"communitys\":[\"741\",\"852\"],\"username\":\"741852\"}")
    public ResponseResult update(HttpServletRequest request,@RequestBody JSONObject jsonObject) {

        if (!Optional.ofNullable(jsonObject.getString("username")).isPresent() ||
                !Optional.ofNullable(jsonObject.getString("firstPassword")).isPresent() ||
                !Optional.ofNullable(jsonObject.getString("tel")).isPresent()) {
            return ResponseResult.builder().code(ResultCode.PARAM_NOT_COMPLETE.getCode()).data(ResultCode.PARAM_NOT_COMPLETE.getMessage()).build();
        }
        String password = jsonObject.getString("firstPassword");

        PasswprdUtil.contains(password,0,jsonObject.getString("username"),0);
        return sysUserService.update(request,jsonObject);
    }
    
    @RequiresAuthentication
    @PostMapping("/delete")
    @ApiOperation(value = "用户管理-用户删除", httpMethod = "POST", notes = "{\"id\":\"255762da-3072-4b60-898b-5bc8142250c6\"}")
    public ResponseResult delete(HttpServletRequest request,@RequestBody JSONObject jsonObject) {

        if (!Optional.ofNullable(jsonObject.getString("id")).isPresent()) {
            return ResponseResult.builder().code(ResultCode.PARAM_NOT_COMPLETE.getCode()).data(ResultCode.PARAM_NOT_COMPLETE.getMessage()).build();
        }

        return sysUserService.deleteById(request,jsonObject.getString("id"));
    }

    @RequiresAuthentication
    @PostMapping("/rolechages")
    @ApiOperation(value = "用户管理-用户批量分配角色", httpMethod = "POST", notes = "{\"users\":[\"用户id\"],\"role\":\"角色id\"}")
    public ResponseResult roleChages(HttpServletRequest request,@RequestBody JSONObject jsonObject) {
        return sysUserService.roleChages(request,jsonObject);
    }

    @RequiresAuthentication
    @PostMapping("/comchages")
    @ApiOperation(value = "用户管理-用户批量分配社区权限", httpMethod = "POST", notes = "{\"users\":[\"用户id\"],\"role\":\"社区id\"}")
    public ResponseResult comChages(HttpServletRequest request,@RequestBody JSONObject jsonObject) {
        return sysUserService.comChages(request,jsonObject);
    }

    @RequiresAuthentication
    @PostMapping(value = "/list")
    @ApiOperation(value = "用户管理-列表查询", httpMethod = "POST", notes = "")
    public ResponseResult list(@RequestParam(required = false,defaultValue = "") String condition,
                               @RequestParam(value = "page",defaultValue = "1") Integer page,
                               @RequestParam(required = false,defaultValue = "") String useTime,
                               @RequestParam(required = false,defaultValue = "") String account,
                               @RequestParam(value = "limit",defaultValue = "18") Integer limit) {
        return sysUserService.selectPage(page, limit, condition,useTime,account);
    }
    
//    /**
//     * 登陆
//     */
//    @PostMapping(path = {"/login"})
//    public ResponseResult login(@RequestBody @Validated User user) throws UnsupportedEncodingException {
//        return sysUserService.login(user);
//    }

//    /**
//     * 登陆之后，返回给前端的数据
//     */
//    @RequiresAuthentication
//    @GetMapping(path = {"/userinfo"})
//    public ResponseResult userInfo(){
//        return sysUserService.userInfo();
//    }
//
//    /**
//     * 查询用户的社区权限，以及每个社区下的多个小区信息
//     */
//    @RequiresAuthentication
//    @GetMapping(path = "/find/community/polt")
//    public ResponseResult findByCommunityAndPolt(){
//        return sysUserService.findByCommunityAndPolt();
//    }

//    /**
//     * 退出
//     */
//    @RequiresAuthentication
//    @GetMapping(path = {"/logout"})
//    public ResponseResult logout(HttpServletRequest request) {
//        return sysUserService.logout(request);
//    }

    @RequiresAuthentication
    @PostMapping("/reset")
    @ApiOperation(value = "用户管理-密码重置", httpMethod = "POST", notes = "")
    public ResponseResult reset(HttpServletRequest request,@RequestBody JSONObject id) {
        return sysUserService.reset(request,id.getString("id"));
    }

//    @RequiresAuthentication
    @PostMapping("/passwordchage")
    @ApiOperation(value = "用户管理-用户批量分配社区权限", httpMethod = "POST", notes = "id:记录id,oldPassword旧密码,newPassword新密码")
    public ResponseResult passwordchage(HttpServletRequest request,@RequestBody JSONObject jsonObject) {
        if (!Optional.ofNullable(jsonObject.getString("oldPassword")).isPresent() ||
                !Optional.ofNullable(jsonObject.getString("newPassword")).isPresent()) {
            return ResponseResult.builder().code(ResultCode.PARAM_NOT_COMPLETE.getCode()).data(ResultCode.PARAM_NOT_COMPLETE.getMessage()).build();
        }
        return sysUserService.passwordchage(request,jsonObject);
    }

    @RequiresAuthentication
    @PostMapping("/deletes")
    @ApiOperation(value = "用户管理-批量用户删除", httpMethod = "POST", notes = "{\"ids\":[\"255762da-3072-4b60-898b-5bc8142250c6\"]}")
    public ResponseResult deletes(HttpServletRequest request,@RequestBody JSONObject jsonObject) {

        if (!Optional.ofNullable(jsonObject.get("ids")).isPresent()) {
            return ResponseResult.builder().code(ResultCode.PARAM_NOT_COMPLETE.getCode()).data(ResultCode.PARAM_NOT_COMPLETE.getMessage()).build();
        }

        return sysUserService.deleteByIds(request,jsonObject);
    }

    @RequiresAuthentication
    @PostMapping(value = "/dlist")
    @ApiOperation(value = "用户管理-已删除账号", httpMethod = "POST", notes = "")
    public ResponseResult dlist(@RequestParam(required = false,defaultValue = "") String condition,
                               @RequestParam(value = "page",defaultValue = "1") Integer page,
                               @RequestParam(value = "limit",defaultValue = "18") Integer limit) {
        return sysUserService.selectPage2(page, limit, condition);
    }
    @RequiresAuthentication
    @PostMapping("/getback")
    @ApiOperation(value = "用户管理-账号恢复", httpMethod = "POST", notes = "")
    public ResponseResult getback(HttpServletRequest request,@RequestBody JSONObject id) {
        JSONObject jsonObject = id.getJSONObject("entey");
        if (!Optional.ofNullable(jsonObject.getString("username")).isPresent() ||
                !Optional.ofNullable(jsonObject.getString("firstPassword")).isPresent() ||
                !Optional.ofNullable(jsonObject.getString("tel")).isPresent()) {
            return ResponseResult.builder().code(ResultCode.PARAM_NOT_COMPLETE.getCode()).data(ResultCode.PARAM_NOT_COMPLETE.getMessage()).build();
        }
        String password = jsonObject.getString("firstPassword");

        PasswprdUtil.contains(password,0,jsonObject.getString("username"),0);
        ResponseResult update = sysUserService.update(request, jsonObject);
        if (update.getCode().equals(ResultCode.NORMAL.getCode())){
           return sysUserService.getBack(id.getString("id"));
        }else {
            return update;
        }
    }
}
